<?php

Yii::import( "ext.xupload.models.XUploadForm" );
Yii::import( "ext.xupload.models.ImageUploadForm" );

/**
 * XUploadAction
 * =============
 * Basic upload functionality for an action used by the xupload extension.
 *
 * ###Prologue
 * A file uploader is commonly a web application must have.
 * There are pretty enough extensions in the yii project to achieve this
 * (other use flash, other are jquery...). I was suggested to use the xupload.
 * After checking the project code, i noticed the action code
 * that handles the request from the user.
 *
 * ###"Do not repeat yourself (DRY)"
 * Sticking with this motto, and due to the fact I did not want every controller
 * that needs something to be uploaded to have that code plain in it, I created
 * this CAction class.
 * 99% of the code belongs to the xupload author.
 *
 * ###Needless
 * Many of you may think that this CAction is needless, this is somehow
 * true.
 * You could create a controller like <code>XuploadController.php</code> have all
 * the upload actions in there and pass this <code>controller/action<code> to the
 * xupload <code>url</code> property.
 * Even this case you are one step beyond, just create the <code>XuploadController</code>
 * and use this action as in any other controller:
 * ~~~
 * [php]
 * class MyController extends CController
 * {
 *     public function actions()
 *     {
 *         return array(
 *             'upload'=>array(
 *                 //Assuming action exist in the extension folder
 *                 'class'=>'ext.EXUploadAction',
 *             ),
 *         );
 *     }
 * }
 * ###Ending
 * This code is not complicated neither is big enough. There are only 2 properties:
 * - <code>parent_id</code>: Parent folder where the file will be uploaded.
 * - <code>path</code>: Full path of the main uploading folder.
 * Check code and <code>EXUploadAction::init()</code> for more informatin.
 *
 * ###Resources
 * - [xupload](http://www.yiiframework.com/extension/xupload)
 * - [while(true)](http://dmtrs.devio.us/blog/)
 *
 * @version 0.2
 * @author Dimitrios Mengidis, [Asgaroth](http://www.yiiframework.com/user/1883/)
 */
class XUploadAction extends CAction
{
    /**
     * Full path of the main uploading folder.
     * @see XUploadAction::init()
     * @var string
     * @since 0.1
     */
    public $path;
    protected $fileType;
    protected $imageOwner;
    protected $returnImageSize;

    /**
     * Initialize the propeties of this action, if they are not set.
     *
     * @since 0.1
     */
    public function init()
    {
        if (isset($_GET["returnImageSize"]))
        {
            $this->returnImageSize = $_GET["returnImageSize"];
        }
        if (isset($_GET["avatar"]))
        {
            $user = UserFacade::getUserById(Yii::app()->controller->getUserIdFromSession());
            Yii::app()->controller->checkDirExists(UserFacade::getUserUploadsDir($user));
            Yii::app()->controller->checkDirExists(UserFacade::getUserAvatarPath($user));
            $this->path = UserFacade::getUserAvatarPath($user);
            $this->fileType = "image";
        }
        if (isset($_GET["petAvatar"]))
        {
            $this->imageOwner = PetFacade::loadModel($_GET["petAvatar"]);
            Yii::app()->controller->checkDirExists(PetFacade::getPetsDir($this->imageOwner));
            Yii::app()->controller->checkDirExists(PetFacade::getPetUploadsDir($this->imageOwner));
            Yii::app()->controller->checkDirExists(PetFacade::getPetAvatarPath($this->imageOwner));

            $this->path = PetFacade::getPetAvatarPath($this->imageOwner);
            $this->fileType = "image";
        }
        else if (isset($_GET["photo"]))
        {
            $this->imageOwner = PhotoFacade::getPhotoAlbum($_GET["photo"]);
            $this->path = PhotoFacade::getPhotoUploadsDir($this->imageOwner);
            Yii::app()->controller->checkDirExists(PhotoFacade::getPhotoAlbumsUploadsDir());
            Yii::app()->controller->checkDirExists($this->path);            
            $this->fileType = "image";
        }
        else if (isset($_GET["exposition"]))
        {            
            $this->imageOwner = ExpositionFacade::getModel($_GET["exposition"]);                                    
            $this->path = ExpositionFacade::getExpositionUploadsDir($this->imageOwner);                                        
            $this->fileType = "image";
        }
        else if (isset($_GET["advertisement"]))
        {
            $this->imageOwner = AdvertisementFacade::getModel($_GET["advertisement"]);
            $this->path = AdvertisementFacade::getAdvertisementUploadsDir($this->imageOwner);
            $this->fileType = "image";
        }
        else if (isset($_GET["contest"]))
        {
            $this->imageOwner = ContestFacade::loadModel($_GET["contest"]);
            $this->path = ContestFacade::getContestUploadsDir($this->imageOwner);
            $this->fileType = "image";
        }
        else if (isset($_GET["contestimage"]))
        {            
            $this->imageOwner = ContestFacade::getContestImage($_GET["contestimage"]);            
            $this->path = ContestFacade::getContestImageUploadsDir($_GET["contestimage"]);
            $this->fileType = "image";
        }
    }

    /**
     * The main action that handles the file upload request.
     * @since 0.1
     * @author Asgaroth
     */
    public function run()
    {
        $this->init();
        $model = new XUploadForm;
        $model->file = CUploadedFile::getInstance( $model, 'file' );
        $model->mime_type = $model->file->getType();
        $model->size = $model->file->getSize();
        $model->name = $model->file->getName();

        if ( $model->validate() )
        {
            switch ($this->fileType)
            {
                case "image":
                    $this->handleImageUpload($model);
                    break;
            }
        }
        else
        {
            echo CVarDumper::dumpAsString( $model->getErrors() );
            throw new CHttpException( 500, "Could not upload file" );
        }
    }

    public function bindImageToModel($uploadImage)
    {
        if (isset($_GET["avatar"]))
        {
            UserFacade::saveUserAvatar($uploadImage);
        }
        if (isset($_GET["petAvatar"]))
        {
            PetFacade::savePetAvatar($uploadImage, $this->imageOwner);
        }
        else if (isset($_GET["photo"]))
        {
            PhotoFacade::savePhoto($uploadImage, $this->imageOwner);
        }
        else if (isset($_GET["exposition"]))
        {
            ExpositionFacade::saveImage($uploadImage, $this->imageOwner);
        }
        else if (isset($_GET["advertisement"]))
        {
            AdvertisementFacade::saveImage($uploadImage, $this->imageOwner);
        }
        else if (isset($_GET["contest"]))
        {
            ContestFacade::saveContestImage($uploadImage, $this->imageOwner);
        }
        else if (isset($_GET["contestimage"]))
        {
            ContestFacade::saveImage($uploadImage, $this->imageOwner);
        }
    }

    public function handleImageUpload($baseModel)
    {
        $imageForm = new ImageUploadForm;
        $imageForm->attributes = $baseModel->attributes;
        if ($imageForm->validate())
        {
            $path = $this->path;
            $baseModel->genName();
            $path = $path . $baseModel->name;
            $baseModel->file->saveAs( $path );
            $uploadImage = UploadImageFacade::saveImageModel($path);
            $this->bindImageToModel($uploadImage);
            $path = UploadImageFacade::resolveImagePath($uploadImage->image_id, $this->returnImageSize);
            echo json_encode( array( "name" => $baseModel->name,
                                     "path" => $path,
                                     "type" => $baseModel->mime_type,
                                     "size" => $baseModel->getReadableFileSize() ) );
        }
        else
        {
            echo json_encode( array( "errMsg" => "Файл имеет неправильный формат", "type" => $baseModel->mime_type, "size" => "" ) );
        }
    }

}
